package com.vpen.account.demo.service.impl;

import com.vpen.account.demo.entity.AccountUser;
import com.vpen.account.demo.model.dto.LoginDto;
import com.vpen.account.demo.service.AccountLoginService;
import com.vpen.account.demo.service.AccountUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 描述
 *
 * @author 韦鹏
 * @date 2022/8/16 14:25
 */
@Service("usernameLoginService")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UsernameLoginServiceImpl implements AccountLoginService {

    private final AccountUserService accountUserService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public UserDetails getUserByCondition(LoginDto loginDto) {
        AccountUser accountUser = accountUserService.selectOneByUsername(loginDto.getUsername());
        if (!passwordEncoder.matches(loginDto.getPassword(), accountUser.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        return AccountUserDetailServiceImpl.loadUserDetails(accountUser);
    }
}
